//线性表的c语言实现

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 50
typedef int ElemType;
typedef struct {
    ElemType data[MAXSIZE];
    int  length;
}SqList;

#define TRUE 1
#define FALSE 0

typedef enum {
    ERROR = 0,
    OK = 1
}Status;


/*用a返回线性表s的第1个元素(即i-1位置的元素)的值*/
Status GetElem(SqList s,int i,ElemType *a) {
    Status flag;
    if ((s.length = 0) || (i < 1) || (i > s.length))//表为空或者i不在表范围内
        flag = ERROR;/*返回查找失败*/
    else {
        *a = s.data[i - 1];/*表示i-1位置的元素*/
        flag = OK;
    }
    return flag;/*返回查找成功*/
}
/*在线性表s的第一个位置之前插入元素a*/
Status ListInsert(SqList *s,int i,ElemType a) {
    int j;
    Status flag;
    if (s->length == MAXSIZE || (i < 1) || (i > s->length + 1))/*表已满*/
        flag = ERROR; /*返回插入失败*/
    else {
        for (j = s->length - 1; j >= i - 1; j--)//要括入数据的位置以后的元素依次后移一位
        {
            s->data[j + 1] = s->data[j];
        }

        s->data[i - 1] = a;/*数据a插入第i-1位置*/
        s->length++;/*插入后长度加1*/ flag = OK;
    }
    return flag;/*返回插入成功*/
}

/*删除表s的第i个元素，用a表示删除的值*/
Status ListDelete(SqList*s,int i,ElemType *a){
int j;
Status flag;
if(s->length==0||(i<1)||(i>s->length))/*表为空*/
flag=ERROR;/*返回删除错误*/
else{
*a=s->data[i-1];/*a表示要删除的值*/
for(j=i-1;j<s->length;j++)
//要删除元素以后的每个值都向前移动一位
    {
s->data[i]=s->data[j+1];}
s->length--;/*表长度减1*/
flag=OK;
}
return flag;/*返回删除成功*/
}

/*打印表s的所有数据*/
void ListDisplay(SqList *s) {
    int i;
    printf("SqList is:");
    for (i = 0; i < s->length; i++) {
        printf("&d", s->data[i]);
    }
    printf("\n");
}

void main() {
    SqList test;
    test.length = 0;
    ListDisplay(&test);
    int i;
    for (i = 0; i < 10; i++) {
        ListInsert(&test, i, i * 2);
        printf("insert data d,now", i * 2);
        ListDisplay(&test);
    }
    int data = 0;
    GetElem(test, 5, &data);
    printf("SqList test fifth data is 8d\n", data);
    printf("SqList test fifth data is * d\n", test.data[4]);
    int len = test.length;
    for (i = 0; i < len; i++) {
        int b;
        ListDelete(&test, 1, &b);
        printf("delete data & d,now", b);
        ListDisplay(&test);
    }
}

